<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="单据编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billNo"
            >
              <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="单据类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billType"
            >
              <a-input v-model="model.billType" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="单据日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billDate"
            >
              <j-date
                placeholder="请选择日期"
                v-model="model.billDate"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="供货单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierName"
            >
              <!-- <tsl-supplier
                v-model="model.supplierName"
                :isDisabled="formDisabled"
                @handlerOk="onSelectSupplier"
              ></tsl-supplier>-->
              <select-supplier-single
                v-model="model.supplierName"
                :isDisabled="formDisabled"
                @onSuppliersSelected="onSelectSupplier"
              ></select-supplier-single>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="要求到货日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalDate"
            >
              <a-input v-model="model.arrivalDate" placeholder="请输入要求到货日期"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="发件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseBy"
            >
              <a-input v-model="model.purchaseBy" placeholder="请输入发件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="传真电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchasePhone"
            >
              <a-input v-model="model.purchasePhone" placeholder="请输入传真电话"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="需方签章"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseSign"
            >
              <a-input v-model="model.purchaseSign" placeholder="请输入需方签章"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="收件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierBy"
            >
              <a-input v-model="model.supplierBy" placeholder="请输入收件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="传真电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierPhone"
            >
              <a-input v-model="model.supplierPhone" placeholder="请输入传真电话"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="供方签章"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierSign"
            >
              <a-input v-model="model.supplierSign" placeholder="请输入供方签章"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="制单人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createBy"
            >
              <a-input v-model="model.createBy" placeholder="请输入申请人" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="sysOrgCode"
            >
              <j-select-depart disabled v-model="model.sysOrgCode" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-model-item label="特殊要求" prop="specialRequest">
              <a-textarea v-model="model.specialRequest" placeholder :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="packageMaterialPurchaseBillDetailTable.loading"
          :columns="packageMaterialPurchaseBillDetailTable.columns"
          :dataSource="packageMaterialPurchaseBillDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="false"
          :rowSelection="true"
          rowSelectionType="radio"
          @edit-closed="editClosedEvent"
        >
          <template v-slot:action="props">
            <a v-if="props.row.patternFile" @click="handlePreviewFile(props)">查看版样</a>
            <a-divider type="vertical" />
            <a-popconfirm v-show="!formDisabled" title="确定删除吗？" @confirm="handleDelDetail(props)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { getAction, httpAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import store from '@/store'
import moment from 'dayjs'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import TslSupplier from '@comp/tsl/TslSupplier.vue'
import { FilePreview } from '@/utils/tslCommon'
import SelectSupplierSingle from '@comp/base/SelectSupplierSingle'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'PackageMaterialPurchaseBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    TslSupplier,
    SelectSupplierSingle,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        billNo: '',
        billDate: '',
        packageMaterialPurchaseBillDetailList: [],
        billType: '',
        purchaseBy: '郑惠铭',
        purchasePhone: '0535-8913889',
        arrivalDate: '',
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        billDate: [{ required: true, message: '请选择订单日期!' }],
        supplierName: [{ required: true, message: '请选择供方单位!' }],
        arrivalDate: [{ required: true, message: '请输入要求到货日期!' }],
        purchaseBy: [{ required: true, message: '请输入发件人!' }],
        supplierBy: [{ required: true, message: '请输入收件人!' }],
      },
      refKeys: ['packageMaterialPurchaseBillDetail'],
      tableKeys: ['packageMaterialPurchaseBillDetail'],
      activeKey: 'packageMaterialPurchaseBillDetail',
      // 包材采购订单子表
      packageMaterialPurchaseBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'seq',
            type: JVXETypes.normal,
            width: '60px',
            placeholder: '请输入${title}',
          },
          {
            title: '排产单号',
            key: 'orderNo',
            type: JVXETypes.normal,
            width: '90px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '成品名称',
            key: 'productName',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '成品规格',
            key: 'productSpec',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单数量',
            key: 'oderNum',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '包材编号',
            key: 'materialNo',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '包材名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格',
            key: 'spec',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '包装类别',
            key: 'packageType',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '总数量(个)',
            key: 'allNum',
            type: JVXETypes.normal,
            width: '90px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库存',
            key: 'stockNum',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            type: JVXETypes.normal,
            width: '50px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '比例数量',
            key: 'bomRate',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '损耗率(%)',
            key: 'badRate',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '数量',
            key: 'num',
            type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '是否有版样',
            key: 'isHavePattern',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '下单日期',
            key: 'orderDate',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '包材到位日期',
            key: 'packageArrivalDate',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '交货时间',
            key: 'custRequestDate',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '订单要求',
            key: 'request',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '供方确认日期',
            key: 'supplierConfirmDate',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '160px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/procurement/packageMaterialPurchaseBill/add',
        edit: '/procurement/packageMaterialPurchaseBill/edit',
        queryById: '/procurement/packageMaterialPurchaseBill/queryById',
        packageMaterialPurchaseBillDetail: {
          list: '/procurement/packageMaterialPurchaseBill/queryPackageMaterialPurchaseBillDetailByMainId',
        },
      },
      unitDictOptions: {},
      zlunitDictOptions: {},
      patternDictOptions: {},
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    this.model.billDate = moment().format('YYYY-MM-DD')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.sysOrgCode = user.departIds
    }

    this.initDictConfig()
    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    generateBillNo() {
      let url = '/sys/fillRule/executeRuleByCode/package_material_purchase_bill'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.billNo = res.result
        }
      })
    },
    addBefore() {
      this.packageMaterialPurchaseBillDetailTable.dataSource = []
    },
    add() {
      this.generateBillNo()

      this.packageMaterialPurchaseBillDetailTable.dataSource = []

      let tempList = store.getters.selectSaleOrderDetail

      console.log('排产单', tempList)
      if (tempList.length > 0) {
        this.model.billType = tempList[0].documentType_dictText
        this.model.arrivalDate = tempList[0].deliveryDate
        getAction('/review/bussInternationalTradeOrders/queryPackagesByOrder', { code: tempList[0].code }).then(
          (res) => {
            if (res && res.result && res.result.length > 0) {
              console.log('------------', res.result)
              res.result.forEach((row, index) => {
                this.packageMaterialPurchaseBillDetailTable.dataSource.push({
                  materialId: row.packageId,
                  materialNo: row.packageCode,
                  materialName: row.packageName,
                  spec: row.packageSpec,
                  request: row.materialQuality,
                  seq: index + 1,
                  orderNo: row.orderCode,
                  badRate: row.lossRate,
                  bomRate: row.proportion,
                  productId: row.productId,
                  productNo: row.productCode,
                  productName: row.productName,
                  productSpec: row.productSpec,
                  oderNum: row.mainQuantity,
                  allNum: (row.mainQuantity * row.proportion).toFixed(0),
                  num: (row.mainQuantity * row.proportion * (1 + row.lossRate / 100)).toFixed(0),
                  unit: this.unitDictOptions[row.meUnit],
                  packageArrivalDate: tempList[0].packageInPlace,
                  packageType: row.packageInOutType,
                  custRequestDate: tempList[0].deliveryTime,
                  orderDate: tempList[0].createTime,
                  isHavePattern: this.patternDictOptions[row.isPattern],
                  patternFile: row.patternFile,
                  patternFile: row.patternFile,
                  orderProductId: row.orderProductId,
                })
              })
            }
          }
        )
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.packageMaterialPurchaseBillDetail.list,
          params,
          this.packageMaterialPurchaseBillDetailTable
        )
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        packageMaterialPurchaseBillDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    initDictConfig() {
      //初始化字典 - 主单位
      initDictOptions('ji_unit').then((res) => {
        var unitDictOptions = this.unitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
      //初始化字典 - 辅单位
      initDictOptions('zl_unit').then((res) => {
        var zlunitDictOptions = this.zlunitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            zlunitDictOptions[item.value] = item.label
          })
        }
        this.zlunitDictOptions = zlunitDictOptions
      })
      //初始化字典 - 是否有版样
      this.patternDictOptions = {
        1: '是',
        0: '否',
      }
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      if (this.packageMaterialPurchaseBillDetailTable.dataSource.length > 0) {
        this.packageMaterialPurchaseBillDetailTable.dataSource.splice(
          this.packageMaterialPurchaseBillDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
          1
        )

        this.packageMaterialPurchaseBillDetailTable.dataSource.forEach((element, index) => {
          element.seq = index + 1
        })
      }
    },
    onSelectSupplier(record) {
      this.model.supplierName = record.name
      this.model.supplierId = record.id
      this.model.supplierNo = record.code
      this.model.supplierBy = record.contact
      this.model.supplierPhone = record.telephone
      this.$forceUpdate()
    },
    handlePreviewFile(props) {
      console.log(props.row, '版样文件')
      FilePreview(props.row.patternFile)
    },
    editClosedEvent({ row, column, cellValue }) {
      if (column.property === 'badRate') {
        //如果输入数量或者价格时自动计算总价格
        if (row.allNum && row.badRate) {
          row.num = (row.allNum * (1 + row.badRate / 100.0)).toFixed(0)
          //this.$forceUpdate()
        }
      }
    },
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true

      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            //241119修改提交时还要判断是否直接进入审批流
            if (!this.model.id) {
              this.model.dataId = res.message
              this.applySubmit(this.model)
            }
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'packageMaterialPurchaseBillService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
  },
}
</script>

<style scoped></style>
